﻿using System;
using System.Windows;
using System.Windows.Media.Imaging;
using System.Runtime.InteropServices;
using System.Drawing;

using Emgu.CV.CvEnum;
using Emgu.CV.Structure;
using Emgu.CV;

namespace WpfFaceDetectionTest
{
    public static class ImageUtils
    {
        public static Image<Bgr, Byte> MergeWithFrame(Image<Bgr, Byte> backImage, Image<Bgr, Byte> frontImage)
        {
            var backImageBitMap = backImage.ToBitmap();
            var graphic = Graphics.FromImage(backImageBitMap);

            graphic.DrawImage(frontImage.ToBitmap(), new Rectangle(0, 0, frontImage.Width, frontImage.Height));

            return new Image<Bgr, Byte>(backImageBitMap);
        }

        public static Image<Bgr, Byte> MergeWithFrame(Image<Bgr, Byte> backImage, Image frontImage)
        {
            var backImageBitMap = backImage.ToBitmap();
            var graphic = Graphics.FromImage(backImageBitMap);

            graphic.DrawImage(new Bitmap(frontImage), new Rectangle(0, 0, frontImage.Width, frontImage.Height));

            graphic.Dispose();
            backImage.Dispose();

            return new Image<Bgr, Byte>(backImageBitMap);
        }

        public static BitmapSource ToBitmapSource(IImage image)
        {
            using (var source = image.Bitmap)
            {
                var ptr = source.GetHbitmap(); //obtain the Hbitmap

                var bs = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
                    ptr,
                    IntPtr.Zero,
                    Int32Rect.Empty,
                    BitmapSizeOptions.FromEmptyOptions());

                DeleteObject(ptr); //release the HBitmap
                return bs;
            }
        }

        [DllImport("gdi32")]
        private static extern int DeleteObject(IntPtr o);
    }
}
